# coding = "utf-8"
import json
import time
import ColorControl
import requests as req

host = 'daka.zcmu.edu.cn'
head = {
    "Host": host,
    "Connection": "keep-alive",
    "Upgrade-Insecure-Requests": "1",
    "User-Agent": "Mozilla/5.0 (Linux; Android 6.0.1; MuMu Build/V417IR; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/66.0.3359.158 Mobile Safari/537.36 wxwork/3.1.16 ColorScheme/Light MicroMessenger/7.0.1 NetType/WIFI Language/zh Lang/zh",
    "Sec-Fetch-Dest": "document",
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
    "Accept-Language": "zh-CN,zh;q=0.9"
}


# 查找json内容函数
def findAns(data, answer):
    for i in data:
        if i["OPTION"] == answer:
            return i["SUBID"]


# 打卡函数
def clockIn(name, num, replaceAns):
    # 获取问卷
    data = {"pageNum": 1, "nodataFlag": 'false', "pageSize": 10, "userId": num}
    que = req.post(url='https://daka.zcmu.edu.cn/questionnaireSurvey/queryQuestionnairePageList',
                   data=data,
                   headers=head)
    while que.status_code == 404:
        time.sleep(30)
        que = req.post(url='https://daka.zcmu.edu.cn/questionnaireSurvey/queryQuestionnairePageList',
                       data=data,
                       headers=head)
    json_queId = que.text
    try:
        queId = json.loads(json_queId)['rows'][0]['ID']
    except:
        time_now = time.strftime("%H:%M:%S", time.localtime())
        ColorControl.printRed(time_now + "——" + num + name + ': 500 Failed')
        ColorControl.printWhite("")
        return 500
    # 获取问卷
    data = {"questionnaireId": queId, "userId": num}
    json_que = req.post(
        url=
        'https://daka.zcmu.edu.cn/questionnaireSurvey/queryQuestionnaireDetail',
        data=data,
        headers=head).text
    que = json.loads(json_que)
    que = que["rows"]
    problems = []
    for i in range(1, len(que)):
        problems.append(que[i])
    # 打卡核心
    ans = []
    for i in problems:
        pType = i["TYPE"]
        title = i['TITLE']
        a = ""
        if title in replaceAns:
            if pType == 'textFill' or pType == 'areaFill':
                a = replaceAns[title]["ANSWERTEXT"]
            elif pType == 'radio' or pType == 'checkbox':
                op = i['OPTIONS']
                a = findAns(op, replaceAns[title]["ANSWERTEXT"])
        else:
            if pType == 'textFill' or pType == 'areaFill':
                a = i["ANSWERTEXT"]
            elif pType == 'radio' or pType == 'checkbox':
                for j in i["OPTIONS"]:
                    if j["CHECKED"]:
                        a = j["SUBID"]
                        break
        ans.append('{"itemId":"' + i["ITEMID"] + '","itemType":"' +
                   i["TYPE"] + '","answerArr":["' + a + '"]}')
    res = '{"answerData":['
    f = True
    for i in ans:
        if f:
            f = False
        else:
            res += ','
        res += i
    res += ']}'
    data = {"questionnaireId": queId, "userId": num, "answerData": res}
    status = req.post(
        url=
        'https://daka.zcmu.edu.cn/questionnaireSurvey/addQuestionnaireRecord',
        data=data,
        headers=head).text
    time_now = time.strftime("%H:%M:%S", time.localtime())
    ColorControl.printGreen(time_now + "——" + num + name + ': 200 Success')
    # print(status)
    ColorControl.printWhite("")
    return 200
